<template>
  <div class="wrapper">
    <div class="main">
      <div class="search-bar">
        <el-select v-model="searchPost.craftBelongId" filterable placeholder="请所属模块" style="width: 220px;">
          <el-option value="" label="全部"></el-option>
          <el-option v-for="item in dictList" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
        <div class="btn-group">
          <el-button type="primary" size="mini" @click="getCraftList(true)">查询</el-button>
        </div>
      </div>
      <div class="table">
        <el-table :height="tableHeight+'px'" :data="craftList.list" @selection-change="handleSelectionChange" border style="width: 100%">
          <el-table-column
            type="selection"
            align="center"
            width="55">
          </el-table-column>
          <el-table-column label="序号" align="center" width="80">
            <template slot-scope="scope">{{scope.$index+1}}</template>
          </el-table-column>
          <el-table-column prop="craftName" label="工艺名称" align="center" min-width="150"></el-table-column>
          <el-table-column prop="craftBelongName" label="所属模块" align="center" min-width="150"></el-table-column>
          <el-table-column label="操作" align="center" min-width="100">
            <template slot-scope="scope">
              <el-button @click.native.prevent="openEditDialog(scope)" :disabled="!hasAuthority" type="text" size="small">编辑</el-button>
              <el-button @click.native.prevent="delCraft(scope.row)" :disabled="!hasAuthority" type="text" size="small">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="bottom">
        <div class="btn-wrapper">
          <el-button type="primary" size="mini" @click="openEditDialog" :disabled="!hasAuthority">新增</el-button>
          <el-button type="primary" size="mini" @click="delAll" :disabled="multipleSelection.length === 0 || !hasAuthority">批量删除</el-button>
          <el-button type="primary" size="mini" @click="$refs.uploadInput.click()" :disabled="!hasAuthority">批量导入</el-button>
          <input ref="uploadInput" type="file" style="display: none;" @change="uploadFile($event)">
          <el-button type="primary" size="mini" @click="exportCraft">导出工艺模板</el-button>
        </div>
        <el-pagination background layout="prev, pager, next" :total="pageConfig.totalCount" :page-size="pageConfig.pageSize" :current-page.sync="pageConfig.pageIndex" @current-change="currentChangeHandle"></el-pagination>
      </div>
    </div>
    <el-dialog :title="!form.id ? '新增工艺' : '编辑工艺'" :visible.sync="dialogVisible" width="600px">
      <el-form label-width="80px" label-position="left">
        <el-form-item label="工艺名称">
          <span style="color: red; position:absolute; left: -90px;">*</span>
          <el-input v-model="form.craftName" placeholder="请输入工艺名称"></el-input>
        </el-form-item>
        <el-form-item label="所属模块">
          <span style="color: red; position:absolute; left: -90px;">*</span>
          <el-select ref="labelSelected" v-model="form.craftBelongId" filterable placeholder="请选择所属模块" style="width: 100%;">
            <el-option v-for="item in dictList" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" style="display: flex; justify-content: space-between;">
        <div>
          <!-- <el-button @click="delCraft(false)" size="mini" v-if="form.id">删除</el-button> -->
        </div>
        <div>
          <el-button @click="dialogVisible = false" size="mini">取消</el-button>
          <el-button type="primary" @click="submitForm" size="mini">提交</el-button>
        </div>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import formUtil from '@/utils/formUtil'
export default {
  name: '',
  data () {
    return {
      tableHeight: '',
      dialogVisible: false,
      form: {
        craftName: '',
        craftBelongId: '',
        craftBelongName: ''
      },
      dictList: [],
      craftList: {},
      pageConfig:{
        pageIndex: 1,
        pageSize: 15,
        totalCount: 0
      },
      searchPost: {
        craftBelongId: ''
      },
      multipleSelection: [],
      authorityAsd: {},
    };
  },
  components: {},
  mounted () {
    this.tableHeight = document.documentElement['clientHeight'] - 200
    window.onresize = () => {
      this.tableHeight = document.documentElement['clientHeight'] - 200
    }
    this.getAuthorityAsd();
    this.getDictList();
  },
  computed: {
    hasAuthority() {
      return this.authorityAsd.userLevel === '1'
    }
  },
  methods: {
    async getAuthorityAsd() {
      this.authorityAsd = await this.$httpN.postB('pc/authority/asd')
    },
    async getDictList() {
      let data = await this.$httpN.postB('pc/dict/list', {
        searchType: '',
        pid: '1293101384636657666',
        limit: 999
      });
      this.dictList = data.list;
      this.getCraftList(true);
    },
    currentChangeHandle (val) {
      this.pageConfig.pageIndex = val
      this.getCraftList()
    },
    //获取工艺列表
    async getCraftList(type) {
      if(type) this.pageConfig.pageIndex = 1
      this.craftList = await this.$httpN.postB('pc/craft/list',{
        page: this.pageConfig.pageIndex,
        limit: this.pageConfig.pageSize,
        craftBelongId: this.searchPost.craftBelongId
      });
      this.pageConfig.totalCount = this.craftList.totalCount
    },
    openEditDialog(data) {
      formUtil.resetData(this.form);
      if(data.row) this.form = JSON.parse(JSON.stringify(data.row));
      this.dialogVisible = true;
    },
    async submitForm() {
      if(!this.form.craftName) return this.$message.error('请输入工艺名称');
      if(!this.form.craftBelongId) return this.$message.error('请选择所属模块');
      this.form.craftBelongName = this.$refs['labelSelected'].selectedLabel;

      var data = {
        craftName: this.form.craftName,
        craftBelongId: this.form.craftBelongId,
        craftBelongName: this.form.craftBelongName
      }
      if(this.form.id) data.id = this.form.id

      if(!await this.$httpN.postB(!this.form.id ? 'pc/craft/save' : 'pc/craft/update', data)) return
      formUtil.submitSuccess('保存成功');
      this.getCraftList(true);
      this.dialogVisible = false;
    },
    async delCraft(data) {
      let id = data ? data.id : this.form.id;
      formUtil.submitConfirm('请问您是否确定删除该工艺？', async ()=> {
        if(!await this.$httpN.postB('pc/craft/delete', {ids: id, craftNames: data.craftName})) return;
        formUtil.submitSuccess('删除成功');
        this.getCraftList(true);
        this.dialogVisible = false;
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    async delAll() {
      let ids = this.multipleSelection.map(item => item.id);
      let craftNames = this.multipleSelection.map(item => item.craftName);
      formUtil.submitConfirm('请问您是否确定删除该工艺？', async ()=> {
        if(!await this.$httpN.postB('pc/craft/delete', {ids: ids.join(','), craftNames: craftNames.join(',')})) return;
        formUtil.submitSuccess('删除成功');
        this.getCraftList(true);
      })
    },
    async exportCraft() {
      let fileData = await this.$httpN.get('pc/craft/templateExport', {}, 'blob');
      this.downFile(fileData, '工艺模板.xls');
    },
    downFile(blob, fileName) {
      if (window.navigator.msSaveOrOpenBlob) {
        navigator.msSaveBlob(blob, fileName);
      } else {
        var link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = fileName;
        link.click();
        window.URL.revokeObjectURL(link.href);
      }
    },
    uploadFile(e) {
      let file = e.target.files[0];
      var formData = new FormData();
      formData.append("file", file);
      formData.append("name", 'file');
      this.$httpN.upload('pc/craft/fileUpload', formData).then((res) => {
        if(res.status === 200 && res.data.code === 0) {
          formUtil.submitSuccess('上传成功')
          this.getCraftList(true);
        }else{
          this.$message.error('上传文件出错,请重试')
        }
      })
      e.target.value = '';
    }
  }
}
</script>

<style lang='scss' scoped>
.wrapper {
  height: 100%;
  width: 100%;
  padding: 0 15px;
  .main {
    height: 100%;
    padding: 15px 0;
    .search-bar {
      padding-bottom: 15px;
      display: flex;
      .btn-group {
        margin-left: 10px;
        line-height: 36px;
      }
    }
    .table {
      height: calc(100% - 93px);
      overflow: auto;
    }
    .bottom {
      height: 54px;
      padding: 13px 0;
      display: flex;
      justify-content: space-between;
      .btn-wrapper {
        white-space: nowrap;
        overflow-x: auto;
        overflow-y: hidden;
        &::-webkit-scrollbar {
          width: 4px;
          height: 4px;
        }
        &::-webkit-scrollbar-thumb {/*滚动条里面小方块*/
          border-radius: 5px;
          background: rgba(0,0,0,0.2);
          scrollbar-arrow-color:red;
        }
        &::-webkit-scrollbar-track {/*滚动条里面轨道*/
          border-radius: 0;
          background: rgba(0,0,0,0.1);
        }
      }
    }
  }
}
</style>